package com.zhilei.mq;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 短信消息的生产者
 *
 * @author 志磊
 */
@Configuration
public class RabbitMQSMSConfig {

    public static final String SMS_EXCHANGE = "sms_exchange";

    public static final String SMS_QUEUE = "sms_queue";

    public static final String ZHILEI_SMS_SEND = "zhilei.sms.send";

    // 声明一个交换机
    @Bean(SMS_EXCHANGE)
    public Exchange exchange() {
        return ExchangeBuilder
                .topicExchange(SMS_EXCHANGE)
                .durable(true)
                .build();
    }

    // 声明一个队列
    @Bean(SMS_QUEUE)
    public Queue queue() {
        return QueueBuilder
                .durable(SMS_QUEUE)
                // TODO 设置超时时间
                .withArgument("x-message-ttl", 10 * 1000)
                // TODO 当消息队列的长度超过6，其他的消息全部进入死信队列进行丢弃
                .withArgument("x-max-length", 6)
                // TODO 定义死信转发到dead.sms.display的exchange
                .withArgument("x-dead-letter-exchange", RabbitMQConfig_Dead.SMS_EXCHANGE_DEAD)
                // TODO 定义死信转发的routingKey
                .withArgument("x-dead-letter-routing-key", RabbitMQConfig_Dead.ROUTING_KEY_SMS_DEAD)
                .build();
    }

    // 将队列和交换机绑定
    @Bean
    public Binding smsBinding(@Qualifier(SMS_EXCHANGE) Exchange exchange,
                              @Qualifier(SMS_QUEUE) Queue queue) {
        return BindingBuilder
                .bind(queue)
                .to(exchange)
                .with("zhilei.sms.#")
                .noargs();
    }

}


















